package com.sparrow.source.service.impl;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sparrow.source.common.dto.IasUserQueryRequest;
import com.sparrow.source.common.dto.UserVerifyLog;
import com.sparrow.source.persistense.IasDeviceUser;
import com.sparrow.source.persistense.IasFace;
import com.sparrow.source.persistense.IasUser;
import com.sparrow.source.persistense.IasVerifyReport;
import com.sparrow.source.persistense.mapper.IasUserMapper;
import com.sparrow.source.service.IIasFaceService;
import com.sparrow.source.service.IIasUserService;
import com.sparrow.source.service.IIasVerifyReportService;
import com.sparrow.source.service.IasDeviceUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author bryceyung
 * @since 2024/11/19
 */
@Service
@Slf4j
public class IasUserServiceImpl extends ServiceImpl<IasUserMapper, IasUser> implements IIasUserService {

    @Autowired
    private IIasFaceService faceService;

    @Autowired
    private IasDeviceUserService deviceUserService;

    @Override
    public IasUser getByUid(Integer uid) {
        return baseMapper.getByUid(uid);
    }

    @Override
    public IPage<IasUser> queryUserPage(IasUserQueryRequest queryRequest, Page<IasUser> page) {
        Page<IasUser> pages = baseMapper.selectWithParam(queryRequest.getUid(), queryRequest.getName(),
                queryRequest.getTel(), page);
        List<IasUser> pageList = pages.getRecords();
        if (CollectionUtils.isEmpty(pageList)) {
            return pages;
        }
        //查找人员人脸信息并组装
        for (IasUser iasUser : pageList) {
            List<IasFace> faceList = faceService.queryByUserId(iasUser.getId());
            iasUser.setFaceList(faceList);
        }
        pages.setRecords(pageList);
        return pages;
    }

    @Override
    public Boolean saveOrUpdateBatchByUid(List<IasUser> userList) {
        List<IasUser> dbLists = this.lambdaQuery().eq(IasUser::getDeleted, false).list();
        //筛选出在userList中不存在的数据
        List<IasUser> deleteList = dbLists.stream().filter(db -> !userList.stream().anyMatch(param ->
                param.getUid().equals(db.getUid()))).collect(Collectors.toList());
        if (deleteList.size() > 0) {
            deleteList.forEach(data -> {
                data.setDeleted(true);
                data.setSyncTime(new Date());
            });
            this.saveOrUpdateBatch(deleteList);
        }
        List<IasUser> saveOrUpdateList = dbLists.stream().filter(db -> userList.stream().anyMatch(param ->
                param.getUid().equals(db.getUid()))).collect(Collectors.toList());
        Map<Integer, IasUser> userMap = saveOrUpdateList.stream().collect(Collectors.toMap(IasUser::getUid, user -> user));
        userList.forEach(data -> {
            IasUser user = userMap.get(data.getUid());
            if (user != null) {
                data.setId(user.getId());
            }
        });
        return saveOrUpdateBatch(userList);
    }

    @Override
    public IasUser getById(Integer userId) {
        IasUser user = baseMapper.selectById(userId);
        if (user == null) {
            return null;
        }
        List<UserVerifyLog> logList = baseMapper.selectDetailInfoByUid(user.getUid(), 10);
        user.setReportList(logList);
        List<IasFace> faceList = faceService.queryByUserId(userId);
        IasDeviceUser deviceUser = deviceUserService.queryByUid(user.getUid(), null);
        if (deviceUser != null && StringUtils.isNotBlank(deviceUser.getImageData())) {
            IasFace deviceFace = new IasFace();
            deviceFace.setImagePath(deviceUser.getImageData());
            faceList.add(deviceFace);
        }
        user.setFaceList(faceList);
        return user;
    }

    @Override
    public IasUser queryByUserOrPersonId(Long userId) {
        return baseMapper.selectByUserOrPersonId(userId);
    }

    @Override
    public Boolean delete(Integer userId) {
        IasUser user = this.getById(userId);
        if (user == null) {
            log.error("[{user delete}]未找到对应用户信息 {}", userId);
            return false;
        }
        // 删除设备上的人员信息
        user.setDeleted(true);
        return this.updateById(user);
    }
}
